import { useEffect, useState } from 'react';
import { getClientW, getClientH } from '../base/util';

const get_w = (sideopen, minw) => {
    if (!minw) {
        return 0;
    }

    let w = getClientW(sideopen);
    if (w < minw) {
        w = minw;
    }

    return w;
};

const get_h = (mhigh, minh) => {
    if (!minh) {
        return 0;
    }

    let h = getClientH() - mhigh;
    if (h < minh) {
        h = minh;
    }

    return h;
};

const endIndex = (data, width) => {
    let ret = parseInt(width/44, 10);
    if (!ret) {
        ret = 63;
    }

    const len = data.length;

    if (ret >= len) {
        ret = len - 1;
    }

    return ret;
};

const useSize = (sideopen, minw, mhigh, minh) => {
    const [width, setWidth] = useState(get_w(sideopen, minw));
    const [height, setHigh] = useState(get_h(mhigh, minh));

    useEffect(() => {
        const onResize = () => {
            if (minw) {
                setWidth(get_w(sideopen, minw));
            }

            if (minh) {
                setHigh(get_h(mhigh, minh));
            }
        }

        window.addEventListener('resize', onResize)

        return () => window.removeEventListener('resize', onResize);
    }, [sideopen, minw, minh, mhigh]);

    const end_index = (data) => endIndex(data, width);

    return [width, height, end_index];
};

const useWidth = (sideopen, minw) => {
    const [width, setWidth] = useState(get_w(sideopen, minw));

    useEffect(() => {
        const onResize = () => {
            if (minw) {
                setWidth(get_w(sideopen, minw));
            }
        }

        window.addEventListener('resize', onResize)

        return () => window.removeEventListener('resize', onResize);
    }, [sideopen, minw]);

    const end_index = (data) => endIndex(data, width);

    return [width, end_index];
};

const useHigh = (mhigh, minh) => {
    const [height, setHigh] = useState(get_h(mhigh, minh));

    useEffect(() => {
        const onResize = () => {
            if (minh) {
                setHigh(get_h(mhigh, minh));
            }
        }

        window.addEventListener('resize', onResize)

        return () => window.removeEventListener('resize', onResize);
    }, [minh, mhigh]);

    return [height];
};

export {useHigh, useWidth, useSize};
